package com.ruyiadmin.springcloud.producer.controller.core;

import cn.hutool.core.io.FileUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.ruyiadmin.springcloud.producer.common.annotations.core.AllowAnonymous;
import com.ruyiadmin.springcloud.producer.common.annotations.system.Log;
import com.ruyiadmin.springcloud.producer.common.beans.core.MomConfig;
import com.ruyiadmin.springcloud.producer.common.beans.system.DirectoryConfig;
import com.ruyiadmin.springcloud.producer.common.core.business.enums.OperationType;
import com.ruyiadmin.springcloud.producer.common.core.system.entities.ActionResult;
import com.ruyiadmin.springcloud.producer.common.exceptions.RuYiAdminCustomException;
import com.ruyiadmin.springcloud.producer.common.utils.system.RuYiSentinelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 * RuYiAdmin系统服务 前端控制器
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-07-17
 */
@RestController
@RequestMapping("/RuYiAdminSystem")
@Api(tags = "RuYiAdmin系统服务")
@RequiredArgsConstructor
@Slf4j
@EnableConfigurationProperties({MomConfig.class})
public class RuYiAdminSystemController {

    //region 服务私有属性

    private final MomConfig momConfig;
    private final DirectoryConfig directoryConfig;

    //endregion

    //region 获取消息中间件类型

    @GetMapping("/GetMomType")
    @ApiOperation(value = "获取消息中间件类型")
    @AllowAnonymous
    public ActionResult getMomType() throws BlockException {
        RuYiSentinelUtil.tryAcquire("QueryMomType");
        log.info("mom type is {}", this.momConfig.getMomType());
        return ActionResult.success(this.momConfig.getMomType());
    }

    //endregion

    //region 下载Excel提示文件

    @GetMapping("/DownloadExcel/{excelId}")
    @ApiOperation(value = "下载Excel提示文件")
    @Log(OperationType = OperationType.DownloadFile)
    public void downloadExcel(@PathVariable("excelId") String excelId, HttpServletResponse response) {
        FileInputStream fis = null;
        ServletOutputStream sos = null;
        try {
            String fileName = excelId + ".xls";
            String path = this.directoryConfig.getTempPath() + "\\" + fileName;
            //设置响应头
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            fis = new FileInputStream(FileUtil.file(path));
            sos = response.getOutputStream();
            IOUtils.copy(fis, sos);
        } catch (Exception e) {
            throw new RuYiAdminCustomException("download error");
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (sos != null) {
                    sos.flush();
                    sos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //endregion

    //region 下载Excel模板

    @GetMapping("/DownloadTemplate/{templateId}")
    @ApiOperation(value = "下载Excel模板")
    @Log(OperationType = OperationType.DownloadFile)
    public void downloadTemplate(@PathVariable("templateId") String templateId, HttpServletResponse response) {
        FileInputStream fis = null;
        ServletOutputStream sos = null;
        try {
            String fileName = templateId + ".xls";
            // resources下路径，比如文件位置在：resources/file/test.docx
            String path = "templates\\" + fileName;
            //设置响应头
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            ClassPathResource classPathResource = new ClassPathResource(path);
            fis = new FileInputStream(classPathResource.getFile());
            sos = response.getOutputStream();
            IOUtils.copy(fis, sos);
        } catch (Exception e) {
            throw new RuYiAdminCustomException("download error");
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (sos != null) {
                    sos.flush();
                    sos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //endregion

    //region 下载代码Zip包

    @GetMapping("/DownloadZip/{zipId}")
    @ApiOperation(value = "下载代码Zip包")
    @Log(OperationType = OperationType.DownloadFile)
    public void downloadZip(@PathVariable("zipId") String zipId, HttpServletResponse response) {
        FileInputStream fis = null;
        ServletOutputStream sos = null;
        try {
            String fileName = zipId + ".zip";
            String path = this.directoryConfig.getTempPath() + "\\" + fileName;
            //设置响应头
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("RuYiAdmin.zip", StandardCharsets.UTF_8));
            fis = new FileInputStream(FileUtil.file(path));
            sos = response.getOutputStream();
            IOUtils.copy(fis, sos);
        } catch (Exception e) {
            throw new RuYiAdminCustomException("download error");
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (sos != null) {
                    sos.flush();
                    sos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //endregion

}
